<?php
require_once 'Zend/Db/Table/Abstract.php';

class Zend_Db_Tree extends Zend_Db_Table_Abstract
{
    protected $_nodeClass = 'Zend_Db_Tree_Node';

    protected $_treeAdapter;

    public function setOptions(array $options)
    {
        parent::setOptions($options);
        if (isset($options['treeAdapter'])) {
            $this->setTreeAdapter($options['treeAdapter']);
        }
    }

    public function setTreeAdapter(Zend_Db_Tree_Adapter_AdapterInterface $adapter)
    {
        $this->_treeAdapter = $adapter;
        return $this;
    }

    public function getTreeAdapter()
    {
        return $this->_treeAdapter;
    }

    public function getRootNode()
    {
        return $this->createNode($this->_treeAdapter->getRootNode());
    }

    public function rootExists()
    {
        return $this->_treeAdapter->rootExists();
    }

    /**
     * @return int|string The primary key.
     */
    public function createRoot(array $data = array())
    {
        return $this->_treeAdapter->createRoot($data);
    }

    public function getNode($nodeId)
    {
        return $this->createNode($this->_treeAdapter->getNode($nodeId));
    }

    public function createNode(array $data = array())
    {
        if (!class_exists($this->_nodeClass)) {
            require_once 'Zend/Loader.php';
            Zend_Loader::loadClass($this->_nodeClass);
        }
        $cols     = $this->_getCols();
        $defaults = array_combine($cols, array_fill(0, count($cols), null));
        $options = array('data' => $defaults, 'table' => $this);
        $node = new $this->_nodeClass($options);
        $node->setData($data);
        return $node;
    }

    public function getChildNodes($nodeId)
    {
        $nodes = $this->_treeAdapter->getChildNodes($nodeId);
        $node = $this->createNode();
        $node->addNodes($nodes);
        return $node;
    }
}
